package com.mmp.main.servlet.report;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mmp.common.servlet.BasicServlet;
import com.mmp.main.entity.HospitalDevice;
import com.mmp.main.util.Default;
import com.mmp.main.util.Enums;
import com.mmp.main.util.WebUtil;

@WebServlet(urlPatterns = { "/ViewDevicesByCatnDep", "/ViewDevicesStatus" })
public class ViewDevicesByCatnDep extends BasicServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		int siteId = getSessionSiteId(request);
		int locationId = getSessionLocationId(request);
		int department = WebUtil.getParamValueAsInteger(request, "dep", 0);
		int category = WebUtil.getParamValueAsInteger(request, "category", 0);

		Map<Integer, Object> map = new HashMap<Integer, Object>();
		int i = 3;

		String jpql = "SELECT h FROM HospitalDevice h WHERE h.site.id = ? AND h.status NOT IN (?,?)";
		map.put(1, siteId);
		map.put(2, Enums.DEVICE_STATUS.SCRAPPED.getStatus());
		map.put(3, Enums.DEVICE_STATUS.TRANSFERRED.getStatus());

		if (locationId != 0) {
			jpql += " AND h.hospital.id = ?";
			map.put(++i, locationId);
		}

		if (category != 0) {
			jpql += " AND h.category.id = ?";
			map.put(++i, category);
		}

		if (department != 0) {
			jpql += " AND h.hospitalDepartment.id = ?";
			map.put(++i, department);
		}

		jpql += " ORDER BY h.hospital.id, h.hospitalDepartment.name, h.category.id, h.name, h.status";

		List<HospitalDevice> deviceList = dbQueryManager.queryJPQL(jpql, map, HospitalDevice.class);
		if (deviceList == null || deviceList.isEmpty()) {
			announceErorrMessage(request, response, "لا يوجد أجهزة بياناتها موافقة للقسم والفئة التي تم اختيارهما");
			return;
		}

		String uri = WebUtil.getRequestUri(request);
		boolean viewDevicesStatus = "ViewDevicesStatus".equals(uri);

		HashMap params = new HashMap();
		params.put("deviceList", deviceList);

		if (viewDevicesStatus) {
			params.put(Default.REPORT_TITLE_PARAM_NAME, Enums.REPORT_TITLE.HOSPITAL_DEVICES_STATUS.getReportTitle());
			viewPDFReport("rt1-2.jasper", null, params, request, response);
		} else {
			params.put(Default.REPORT_TITLE_PARAM_NAME, Enums.REPORT_TITLE.HOSPITAL_DEVICES.getReportTitle());
			viewPDFReport("rt1.jasper", null, params, request, response);
		}

	}
}
